{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "S+P Week 2 Exercise Question.ipynb",
      "version": "0.3.2",
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "metadata": {
        "id": "D1J15Vh_1Jih",
        "colab_type": "code",
        "cellView": "both",
        "colab": {}
      },
      "source": [
        "!pip install tf-nightly-2.0-preview\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BOjujz601HcS",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "print(tf.__version__)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "Zswl7jRtGzkk",
        "colab": {}
      },
      "source": [
        "def plot_series(time, series, format=\"-\", start=0, end=None):\n",
        "    plt.plot(time[start:end], series[start:end], format)\n",
        "    plt.xlabel(\"Time\")\n",
        "    plt.ylabel(\"Value\")\n",
        "    plt.grid(False)\n",
        "\n",
        "def trend(time, slope=0):\n",
        "    return slope * time\n",
        "\n",
        "def seasonal_pattern(season_time):\n",
        "    \"\"\"Just an arbitrary pattern, you can change it if you wish\"\"\"\n",
        "    return np.where(season_time < 0.1,\n",
        "                    np.cos(season_time * # YOUR CODE HERE # * np.pi),\n",
        "                    #YOUR CODE HERE# / np.exp(#YOUR CODE HERE# * season_time))\n",
        "\n",
        "def seasonality(time, period, amplitude=1, phase=0):\n",
        "    \"\"\"Repeats the same pattern at each period\"\"\"\n",
        "    season_time = ((time + phase) % period) / period\n",
        "    return amplitude * seasonal_pattern(season_time)\n",
        "\n",
        "def noise(time, noise_level=1, seed=None):\n",
        "    rnd = np.random.RandomState(seed)\n",
        "    return rnd.randn(len(time)) * noise_level\n",
        "\n",
        "time = np.arange(10 * 365 + 1, dtype=\"float32\")\n",
        "baseline = # YOUR CODE HERE #\n",
        "series = trend(time, # YOUR CODE HERE#)  \n",
        "baseline = 10\n",
        "amplitude = 40\n",
        "slope = # YOUR CODE HERE#\n",
        "noise_level = # YOUR CODE HERE#\n",
        "\n",
        "# Create the series\n",
        "series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)\n",
        "# Update with noise\n",
        "series += noise(time, noise_level, seed=51)\n",
        "\n",
        "split_time = 3000\n",
        "time_train = time[:split_time]\n",
        "x_train = series[:split_time]\n",
        "time_valid = time[split_time:]\n",
        "x_valid = series[split_time:]\n",
        "\n",
        "window_size = 20\n",
        "batch_size = 32\n",
        "shuffle_buffer_size = 1000\n",
        "\n",
        "plot_series(time, series)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GfUTNqti_lNC",
        "colab_type": "text"
      },
      "source": [
        "Desired output -- a chart that looks like this:\n",
        "\n",
        "![Chart showing upward trend and seasonailty](http://www.laurencemoroney.com/wp-content/uploads/2019/07/plot1.png)"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "4sTTIOCbyShY",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "def windowed_dataset(series, window_size, batch_size, shuffle_buffer):\n",
        "  dataset = tf.data.Dataset.from_tensor_slices(series)\n",
        "  dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)\n",
        "  dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))\n",
        "  dataset = dataset.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1]))\n",
        "  dataset = dataset.batch(batch_size).prefetch(1)\n",
        "  return dataset"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "TW-vT7eLYAdb",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)\n",
        "\n",
        "\n",
        "model = tf.keras.models.Sequential([\n",
        "    tf.keras.layers.Dense(# YOUR CODE HERE #),\n",
        "    tf.keras.layers.Dense(# YOUR CODE HERE #, activation=\"relu\"), \n",
        "    tf.keras.layers.Dense(1)\n",
        "])\n",
        "\n",
        "model.compile(loss=# YOUR CODE HERE #, optimizer=# YOUR CODE HERE#))\n",
        "model.fit(dataset,epochs=100,verbose=0)\n",
        "\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "efhco2rYyIFF",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "forecast = []\n",
        "for time in range(len(series) - window_size):\n",
        "  forecast.append(model.predict(series[time:time + window_size][np.newaxis]))\n",
        "\n",
        "forecast = forecast[split_time-window_size:]\n",
        "results = np.array(forecast)[:, 0, 0]\n",
        "\n",
        "\n",
        "plt.figure(figsize=(10, 6))\n",
        "\n",
        "plot_series(time_valid, x_valid)\n",
        "plot_series(time_valid, results)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-kT6j186YO6K",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "tf.keras.metrics.mean_absolute_error(x_valid, results).numpy()\n",
        "# EXPECTED OUTPUT\n",
        "# A Value less than 3"
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}